package com.cgs.springboottes2secrity.web;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import com.cgs.springboottes2secrity.entity.Admin;
import com.cgs.springboottes2secrity.repository.AdminRepository;
import com.cgs.springboottes2secrity.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cgs
 * @version woNiu 98
 * @date 2023/5/11 10:07
 */
@CrossOrigin
@RestController
@RequestMapping("/api")
public class AdminController {
    @Value("${params.secretKey}")
    private String secretKey;
    @Resource
    private AdminRepository ar;

    @PreAuthorize("hasAuthority('order:list')")    //只有拥有该权限（order:list）才能访问该接口
    @GetMapping("order/list")
    public ResponseResult<Void> test(){
        return ResponseResult.success();
    }
    @RequestMapping("/admin/login")
    public ResponseResult login(@RequestBody Admin admin, HttpServletResponse response){
        Admin a = ar.getByAccount(admin.getAccount());
        if(a ==null){
            return ResponseResult.fail();
        }
        if(a.getPwd().trim().equals(admin.getPwd())){
            String token = JWT.create()
                    .setPayload("id", a.getId())
                    .setPayload("account", a.getAccount())
                    .setKey(secretKey.getBytes())
                    .sign();
            response.setHeader("Authorization", token);
            return ResponseResult.success(a);
        }
        return ResponseResult.fail();
    }
}
